<template>
  <div id="content" :style="`height:${clientHeight}`">
    <el-header>TED英语小程序后台管理</el-header>
    <el-main>
      <div class="headTop">
        <div class="topleft">
          <el-input v-model="parms.title" clearable placeholder="请输入文章标题"></el-input>
          <el-input v-model="parms.author" clearable placeholder="请输入文章作者"></el-input>
          <el-select v-model="parms.year" placeholder="请选择年份" clearable>
            <el-option v-for="item in years" :key="item" :label="`${item}年`" :value="item"></el-option>
          </el-select>
          <el-button type="primary" @click="getlist">搜索</el-button>
        </div>
        <div class="topright">
          <el-button type="primary" icon="el-icon-edit" @click="changetype(1)">类别编辑</el-button>
          <el-button type="primary" icon="el-icon-edit" @click="changeHot">热门编辑</el-button>
          <el-button type="primary" icon="el-icon-plus" @click="editarticle(1)">新建文章</el-button>
        </div>
      </div>
      <el-table
        :data="list"
        border
        :height="tableHeight"
        stripe
        resizable
        style="width: 100%"
        v-loading="loading"
        element-loading-background="rgba(0, 0, 0, 0.5)"
        element-loading-text="数据正在加载中"
      >
        <el-table-column type="index" align="center" label="序号" width="50"></el-table-column>
        <el-table-column prop="title" align="center" label="文章名称"></el-table-column>
        <el-table-column prop="url" align="center" label="文章链接"></el-table-column>
        <el-table-column prop="author" align="center" label="作者"></el-table-column>
        <el-table-column prop="year" align="center" label="年份"></el-table-column>
        <el-table-column prop="customize" align="center" label="属性"></el-table-column>
        <el-table-column prop="image" align="center" label="图片">
          <template slot-scope="scope">
            <img
              v-if="scope.row.image"
              class="thumbimg tbimg"
              :src="scope.row.image"
              alt="商品图片"
              @click="handletbimg(scope.row.image)"
            />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="分类">
          <template slot-scope="scope">
            <el-tag v-for="(item,index) in scope.row.tag" :key="index" class="tagbox">{{item}}</el-tag>
          </template>
        </el-table-column>-->
        <!-- <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" @change="changestatus(scope.row)"></el-switch>
          </template> 
        </el-table-column>-->
        <el-table-column align="center" label="操作" width="200">
          <template slot-scope="scope" >
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="editarticle(2,scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deletearticle(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span class="pagein">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="10"
          :total="total"
          :current-page.sync="pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </span>
    </el-main>

    <el-dialog
      title="编辑文章数据"
      :visible.sync="dialogVisible"
      :modal-append-to-body="false"
      center
      width="50%"
      top="2%"
      :before-close="handleClose"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="ruleForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="ruleForm.author" placeholder="请输入作者"></el-input>
        </el-form-item>
        <el-form-item label="属性" prop="customize">
          <el-input v-model="ruleForm.customize" placeholder="请输入属性"></el-input>
        </el-form-item>
        <el-form-item label="序号" prop="sort">
          <el-input v-model="ruleForm.sort" type="number" placeholder="请输入序号"></el-input>
        </el-form-item>
        <el-form-item label="链接" prop="url">
          <el-input v-model="ruleForm.url" placeholder="请输入链接"></el-input>
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-input v-model="ruleForm.year" type="number" placeholder="请输入年份"></el-input>
          <!-- <el-select v-model="ruleForm.year" placeholder="请选择年份">
            <el-option v-for="item in years" :key="item" :label="`${item}年`" :value="item"></el-option>
          </el-select>-->
        </el-form-item>
        <el-form-item label="类别" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择类别">
            <el-option
              v-for="(item) in types"
              :key="item.id"
              :label="`${item.name}`"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <el-tag
            :key="tag"
            v-for="tag in ruleForm.tag"
            closable
            :disable-transitions="false"
            @close="handleClosetag(tag)"
          >{{tag}}</el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          ></el-input>
          <el-button
            v-else
            v-show="ruleForm.tag.length<5"
            class="button-new-tag"
            size="small"
            @click="showInput"
          >+ 添加标签</el-button>
        </el-form-item>
        <el-form-item label="图片" ref="uploadElement" prop="image" v-if="edit.val==2">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="ruleForm.image" :src="ruleForm.image" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      :title="istype?'类别编辑':'热门编辑'"
      :visible.sync="ishot"
      :modal-append-to-body="false"
      center
      width="30%"
      top="2%"
      :before-close="handleClosehot"
    >
      <el-form
        v-if="ishot && !istype"
        :model="hotobj"
        :rules="rules"
        ref="hotobj"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item v-for="(item,index) in hotobj" :key="item" :label="`热门${index+1}`">
          <el-input v-model="hotobj[index]"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="changeHot(1)">保存</el-button>
        </el-form-item>
      </el-form>
      <div class="butbox" v-if="istype">
        <el-button type="primary" @click="addtype">添加类别</el-button>
      </div>
      <el-form
        v-if="ishot && istype"
        :model="hotobj"
        :rules="rules"
        ref="hotobj"
        label-width="100px"
        class="demo-ruleForm editytpebox"
      >
        <el-form-item v-for="(item,index) in types" :key="item" :label="`类别${index+1}`">
          <el-input v-model="types[index].name"></el-input>
          <el-button
            type="primary"
            icon="el-icon-check"
            circle
            size="mini"
            @click="edittype(1,item)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            size="mini"
            @click="edittype(2,item)"
          ></el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "list",
  data() {
    return {
      parms: {
        title: "",
        year: "",
        author: ""
      },
      edit: {
        val: 1,
        obj: {}
      },
      list: [],
      hotobj: [],
      uplpadObj: {},
      total: 0,
      pageNum: 1,
      pageSize: 10,
      ishot: false,
      istype: false,
      loading: false,
      inputVisible: false,
      inputValue: "",
      globalUrl: "http://dev.byn-kj.com:8102/",
      dialogVisible: false,
      years: [],
      types: [],
      ruleForm: {
        title: "",
        author: "",
        customize: "",
        type: 1,
        year: "",
        sort: "",
        tag: [],
        image: "",
        url: ""
      },
      rules: {
        title: [
          {
            required: true,
            message: "请输入文章标题",
            trigger: "blur"
          },
          {
            min: 1,
            max: 150,
            message: "长度在 1 到 150 个字符",
            trigger: "blur"
          }
        ],
        sort: [
          {
            required: true,
            message: "请输入文章序号",
            trigger: "blur"
          },
          {
            min: 1,
            max: 5,
            message: "长度在 1 到 5 个字符",
            trigger: "blur"
          }
        ],
        customize: [
          {
            required: true,
            message: "请输入文章属性",
            trigger: "blur"
          },
          {
            min: 1,
            max: 64,
            message: "长度在 1 到 64 个字符",
            trigger: "blur"
          }
        ],
        author: [
          {
            required: true,
            message: "请输入文章作者",
            trigger: "blur"
          },
          {
            min: 1,
            max: 64,
            message: "长度在 1 到 64 个字符",
            trigger: "blur"
          }
        ],
        url: [
          {
            required: true,
            message: "请输入文章链接",
            trigger: "blur"
          },
          {
            min: 1,
            max: 200,
            message: "长度在 1 到 200 个字符",
            trigger: "blur"
          }
        ],
        year: [
          {
            required: true,
            message: "请输入年份",
            trigger: "blur"
          }
          // {
          //   required: true,
          //   message: "请选择文章年份",
          //   trigger: "change"
          // }
        ],
        type: [
          {
            required: true,
            message: "请选择文章类别",
            trigger: "change"
          }
        ],
        tag: [
          {
            type: "array",
            required: true,
            message: "请至少添加一个标签，最多可添加五个标签",
            trigger: "change"
          }
        ],
        image: [
          {
            required: true,
            message: "请上传图片",
            trigger: "blur"
          }
        ]
      },
      tableHeight: document.documentElement.clientHeight * 0.925 - 140 + "px",
      clientHeight: `${document.documentElement.clientHeight}px`
    };
  },
  mounted() {
    // 动态设置背景图的高度为浏览器可视区域高度

    // 首先在Virtual DOM渲染数据时，设置下背景图的高度．
    // 然后监听window的resize事件．在浏览器窗口变化时再设置下背景图高度．
    const that = this;
    window.onresize = function temp() {
      console.log("onresize");
      that.tableHeight = `${document.documentElement.clientHeight * 0.925 -
        140}px`;
      that.clientHeight = `${document.documentElement.clientHeight}px`;
    };
  },
  watch: {
    dialogVisible: function() {
      if (!this.dialogVisible) {
        for (let key in this.ruleForm) {
          this.ruleForm[key] = "";
        }
        this.ruleForm.tag = [];
      }
    }
  },
  mounted() {
    this.loading = true;
    this.getlist();
  },
  methods: {
    handleClosetag(tag) {
      this.ruleForm.tag.splice(this.ruleForm.tag.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.ruleForm.tag.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    //点击表格图片，查看大图
    handletbimg(val) {
      let imgStr =
        "<img style='width: 100%;margin: 0 auto;' src=" + val + " alt />";
      this.$alert(imgStr, "图片", {
        dangerouslyUseHTMLString: true
      });
    },
    //表格翻页
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getlist();
    },
    //修改每页请求数据条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.getlist();
    },
    // 查询、修改热门
    changeHot(val) {
      let _Url = "article/hot";
      if (this.hotobj.length && val == 1) {
        let parms = {};
        _Url += "?";
        for (let i = 0; i < this.hotobj.length; i++) {
          _Url += `hot${i + 1}=${this.hotobj[i]}&`;
        }
        _Url = _Url.substring(0, _Url.length - 1);
        _Url = encodeURI(_Url);
        this.$http.put(_Url, this.hotobj).then(res => {
          if (res.data == 1) {
            this.$message.success("保存成功");
          }
        });
      } else {
        this.$http.get(_Url).then(res => {
          this.hotobj = Object.keys(res.data).map(key => res.data[key]);
        });
      }
      this.ishot = !this.ishot;
    },
    // 查询分类
    changetype(val) {
      if (val && val == 1) {
        this.ishot = true;
        this.istype = true;
      }
      let _Url = "article/type";
      this.$http.get(_Url).then(res => {
        res.data.map((item, index) => {
          item.edit = true;
        });
        this.types = res.data;
      });
      console.log("types:", this.types);
    },
    addtype() {
      let obj = {
        id: Number(this.types[this.types.length - 1].id) + 1,
        name: ""
      };
      this.types.push(obj);
    },
    savetypes() {},
    edittype(val, obj) {
      console.log(val, obj);
      let _Url = "article/type";
      if (!obj.name) {
        this.$message("请输入类别");
        return;
      }
      if (val == 1) {
        if (obj.edit) {
          delete obj.edit;
          this.$http.put(_Url, obj).then(res => {
            if (res.data == 1) {
              this.$message.success("修改成功");
              this.changetype();
            }
          });
        } else {
          this.$http.post(_Url, obj).then(res => {
            if (res.data == 1) {
              this.$message.success("添加成功");
              this.changetype();
            }
          });
        }
      } else if (val == 2) {
        delete obj.edit;
        this.$http.delete(_Url, { data: obj }).then(res => {
          if (res.data == 1) {
            this.$message.success("删除成功");
            this.changetype();
          }
          console.log(res);
        });
      }
      console.log(obj);
    },
    // 查询文章列表
    getlist() {
      const _this = this;
      let _Url =
        "articleAdmin/article?pageNum=" +
        this.pageNum +
        "&pageSize=" +
        this.pageSize;
      for (let key in this.parms) {
        if (this.parms[key] || this.parms[key] == "0") {
          _Url += "&" + key + "=" + this.parms[key];
        }
      }
      this.$http.get(_Url).then(res => {
        this.loading = false;
        res.data.data.map((item, index) => {
          item.status = item.status == 1 ? true : false;
          if (item.image) {
            item.image = item.image.includes("http")
              ? item.image
              : "https://dev.byn-kj.com/" + item.image;
          }
        });
        this.total = res.data.total;
        this.list = [...res.data.data];
      });
    },
    // 关闭弹框
    handleClose() {
      this.dialogVisible = false;
    },
    handleClosehot() {
      this.ishot = false;
      this.istype = false;
    },
    // 查看大图
    handleChange(file, fileList) {
      this.ruleForm.imageUrl = URL.createObjectURL(file.raw);
    },
    // 修改状态 1有效，2无效
    changestatus(obj) {
      let _Url = "articleAdmin/article/status",
        _parms = {
          status: obj.status ? 1 : 2,
          id: obj.id
        };
      this.$http.put(_Url, _parms).then(res => {
        if (res.data == 1) {
          this.$message.success("修改成功");
          this.getlist();
        }
      });
    },
    // 新建1、编辑2文章
    editarticle(val, obj = {}) {
      console.log("val:", val);
      if (val == 2) {
        this.gettag(obj);
        this.action = this.globalUrl + "articleAdmin/image";
      } else {
        this.edit.obj = { ...obj };
      }
      this.edit.val = val;
      this.dialogVisible = true;
    },
    //删除文章
    deletearticle(obj) {
      let _Url = "articleAdmin/" + obj.id;
      this.$http.delete(_Url).then(res => {
        console.log(res);
        if (res.data == 1) {
          this.$message.success("删除成功");
          this.getlist();
        }
      });
    },
    // 点击文章，根据ID查找文章标签
    gettag(obj) {
      let _Url = "articleAdmin/tag?id=" + obj.id;
      this.$http.get(_Url).then(res => {
        if (res.data && res.data.length) {
          obj.tag = [...res.data];
        } else {
          obj.tag = [];
        }
        this.ruleForm = {
          ...obj
        };
        console.log("ruleForm:", this.ruleForm);
        this.edit.obj = { ...obj };
      });
    },
    beforeUpload(file) {
      return true;
    },
    // 点击确认  验证表单
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.savedata();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 保存数据
    savedata() {
      let _Url = "articleAdmin/article";
      console.log('ruleForm:',this.ruleForm)
      if (this.edit.val == 1) {
        this.$http.post(_Url, this.ruleForm).then(res => {
          if (res.data == 1) {
            this.$message.success("添加成功");
            // this.handleClose();
            // this.getlist();
          }
        });
      } else {
         this.ruleForm.status =  this.ruleForm.status ? 1 : 2;
        this.$http.put(_Url, this.ruleForm).then(res => {
          if (res.data == 1) {
            this.$message.success("修改成功");
            // this.handleClose();
            // this.getlist();
          }
        });
      }
    },
    handleAvatarSuccess(res, file) {
      console.log(res, flle);
      this.ruleForm.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isIMAGE = file.type === "image/jpeg" || "image/jpg" || "image/png";
      //   const isLt300kb = file.size / 1024 < 150;
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isIMAGE) {
        this.isupload = false;
        this.$message.error("上传图上只能是图片JPG或PNG格式!");
      } else if (!isLt2M) {
        this.isupload = false;
        this.$message.error("上传图上大小不能超过1MB!");
      } else {
        this.uplpadObj.file = file;
        this.uplpadObj.id = this.ruleForm.id;
        let index1 = file.name.lastIndexOf(".");
        let index2 = file.name.length;
        let type = file.name.substring(index1, index2);
        let _parms = {},
          _Url = "articleAdmin/image";
        for (let key in this.uplpadObj) {
          if (this.uplpadObj[key]) {
            _parms[key] = this.uplpadObj[key];
          }
        }
        const formData = new FormData();
        Object.keys(_parms).forEach(key => formData.append(key, _parms[key]));
        _parms = formData;
        this.$http.put(_Url, _parms).then(res => {
          if (res.data == 1) {
            this.$message.success("图片修改成功");
            let imgUrl =
              "https://dev.byn-kj.com/static/upload/article/" +
              this.ruleForm.id +
              type;
            this.$set(this.ruleForm, "image", imgUrl);
          } else {
            this.$message.error(res.data);
          }
        });
      }
      return isIMAGE && isLt2M;
    }
  },
  created() {
    this.changetype();
    for (let i = 2025; i > 1999; i--) {
      this.years.push(i);
    }
  }
};
</script>


<style lang="less" scoped>
#content {
  background: url("../assets/images/backgroud.png") no-repeat 100% 100%;
}
header {
  width: 100%;
  font-size: 50px;
  font-weight: bold;
  color: #fff;
  text-align: center;
}

main {
  width: 94%;
  margin: 0 3%;
  min-height: 100px;
}
.editytpebox {
  .el-input {
    width: 70%;
  }
}
.butbox {
  display: flex;
  justify-content: flex-end;
  .el-button {
    margin-bottom: 10px;
  }
}
.headTop {
  width: 100%;
  height: 50px;
  color: #fff;
  padding: 5px 0;
  border-bottom: 2px solid #fff;
}
.topleft {
  float: left;
  .el-input,
  .el-select {
    width: 20%;
    float: left;
    margin-right: 5px;
  }
  .el-button {
    float: left;
  }
}
.topright {
  float: right;
}

.tbimg {
  width: 30px;
  height: 30px;
  cursor: pointer;
}

.tagbox {
  margin: 0 3px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.pagein {
  float: left;
  color: #fff;
}

/* 表单图片 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>


